package com.thread.sync.sync01;

//线程安全Demo
public class MyThread01 extends Thread {
    private int count = 5;

    //synchronized加锁
    public synchronized void run() {
        count--;//自减
        //输出count值
        System.out.println(this.currentThread().getName() + ":count=" + count);
    }

    /**
     * 当一个线程访问myThread的run方法时,以排队的方式进行处理(按照CPU分配的顺序,不是书写顺序),
     * 一个线程想要执行synchronized修饰的方法里的代码:
     * 1 尝试获得锁
     * 2 如果拿到锁,执行synchronized代码体,拿不到,这个线程会不断尝试获取这把锁,直到拿到为止,
     * 而且是多个线程同时去竞争这把锁(锁竞争问题)
     */
    //启用5个线程对同一个MyThread的run方法进行访问,对count值操作并打印
    public static void main(String[] args) {
        //new线程实例并启动
        MyThread01 myThread = new MyThread01();
        Thread t1 = new Thread(myThread, "t1");
        Thread t2 = new Thread(myThread, "t2");
        Thread t3 = new Thread(myThread, "t3");
        Thread t4 = new Thread(myThread, "t4");
        Thread t5 = new Thread(myThread, "t5");
        t1.start();//启动线程
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }

}
